package com.sky.loveshop.config;

import com.sky.loveshop.entity.Result;
import com.sky.loveshop.entity.exception.BizException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.NoHandlerFoundException;

import java.util.HashMap;
import java.util.Map;

/**
 * @author xcy
 * @version V1.0
 * @description
 * @date 2024/8/24 10:15
 */
@ControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    @ExceptionHandler(Exception.class)
    public ResponseEntity<Result> handleException(Exception ex, WebRequest request) {
        log.error("globalException 全局异常", ex);
        Result result = Result.ofError(0, HttpStatus.INTERNAL_SERVER_ERROR.name(), ex.getMessage());
        return new ResponseEntity<>(result, HttpStatus.INTERNAL_SERVER_ERROR);
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseEntity<Result> handleValidationException(MethodArgumentNotValidException ex) {
        log.error("globalMethodArgumentNotValidException", ex);
        ex.printStackTrace();
        BindingResult bindingResult = ex.getBindingResult();
        Map<String, String> errors = new HashMap<>();
        bindingResult.getFieldErrors().forEach(error -> {
            errors.put(error.getField(), error.getDefaultMessage());
        });
        String firstError = bindingResult.getFieldErrors().get(0).getDefaultMessage();

        Result result = Result.ofError(0, "参数校验异常", firstError);

        return new ResponseEntity<>(result, HttpStatus.INTERNAL_SERVER_ERROR);
    }

    @ExceptionHandler(NoHandlerFoundException.class)
    public ResponseEntity<Result> handleNoHandlerFoundException(NoHandlerFoundException ex) {
        log.error("globalNoHandlerFoundException", ex);
        ex.printStackTrace();
        Result result = Result.ofError(0, "访问的路径不存在", ex.getMessage());
        return new ResponseEntity<>(result, HttpStatus.NOT_FOUND);
    }

    @ExceptionHandler(BizException.class)
    public ResponseEntity<Result> handleBizException(BizException ex) {
        log.error("globalBizException {}", ex.getBizExceptionEnum().getMessage());
        ex.printStackTrace();
        if (ex.getBizExceptionEnum().getCode().equals("10026")) {
            Result result = Result.ofError(401, "未认证", ex.getBizExceptionEnum().getMessage());
            return new ResponseEntity<>(result, HttpStatus.UNAUTHORIZED);
        } else {
            Result result = Result.ofError(0, "业务异常", ex.getBizExceptionEnum().getMessage());
            return new ResponseEntity<>(result, HttpStatus.BAD_REQUEST);
        }
    }
}
